# No copyright

import asyncio
import json
import logging
import pybotters
import signal

from util.pair   import Pair
from util.player import Player
from algo.mm     import MM

with open("config.json", "r") as file:
  config = json.load(file)
  
async def main():
  alive = True
  logging.basicConfig(level=logging.DEBUG)

  def teardown():
    nonlocal alive
    alive = False
    for t in asyncio.all_tasks():
      t.cancel()

  loop = asyncio.get_event_loop()
  loop.add_signal_handler(signal.SIGTERM, teardown)
  loop.add_signal_handler(signal.SIGINT,  teardown)

  logging.info("#### TMM ####")
  async with pybotters.Client(apis={"bitbank":config["auth"]}) as pb:
    player = Player(pb)
    pair   = Pair(pb, config["pair"])
    algo   = MM(player, pair, config["algorithm"]["mm"])
    while alive:
      try:
        await asyncio.gather(
          player.update(),
          pair.update())
        await algo.update()
      except Exception as e:
        print(e)
        logging.error(e)
      await asyncio.sleep(int(config["interval"]))

if __name__ == "__main__":
  try:
    loop = asyncio.new_event_loop()
    loop.run_until_complete(main())
  finally:
    loop.close()
